package cn.etgps.etgps.ui;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import cn.etgps.etgps.R;
import cn.etgps.etgps.base.BaseActivity;
import cn.etgps.etgps.blmanager.LoadingManager;
import cn.etgps.etgps.manager.NetworkManager;
import cn.etgps.etgps.utils.AppUtils;
import cn.etgps.etgps.utils.Constant;
import cn.etgps.etgps.view.TitleBar;

/**
 * Created by itte on 2016/1/7.
 */
public class SystemSet extends BaseActivity implements View.OnClickListener {
    private TitleBar mTitleBar = null;
    private EditText mIp = null;
    private EditText mPort = null;
    private Button mSave = null;
    private LoadingManager mLoadingManager = null;
    private String ip = "";
    private String port = "";
    private TestTask mTestTask = null;
    private SharedPreferences mPerference = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_system_set);
        initView();
    }

    private void initView() {
        mTitleBar = (TitleBar) findViewById(R.id.title_bar);
        mTitleBar.initTitleBarInfo(getString(R.string.title_system_set), "", R.drawable.icon_return, "", 0, false);
        mTitleBar.setMainClickListener(this, getString(R.string.btn_back), "");
        mIp = (EditText) findViewById(R.id.et_system_set_ip);
        mPort = (EditText) findViewById(R.id.et_system_set_port);
        mSave = (Button) findViewById(R.id.btn_save);
        mSave.setOnClickListener(this);
        mLoadingManager = new LoadingManager(this);
        mPerference = getSharedPreferences(getString(R.string.preference_key), MODE_PRIVATE);
        String ip = mPerference.getString(getString(R.string.label_system_set_ip), "");
        String port = mPerference.getString(getString(R.string.label_system_set_port), "");
        mIp.setText(ip);
        mPort.setText(port);
    }

    @Override
    public void clickButtonListener(String name) {
        if (name.equals(getString(R.string.btn_back))) {
            exit();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_save:
                ip = mIp.getText().toString().trim();
                port = mPort.getText().toString().trim();
                if (mTestTask != null && mTestTask.getStatus() == AsyncTask.Status.RUNNING) {
                    mTestTask.cancel(true);
                    mTestTask = null;
                }
                mTestTask = new TestTask();
                mTestTask.execute(ip, port);
                break;
        }
    }

    @Override
    public void onBackPressed() {
        exit();
    }

    private void exit() {
        for (Activity activity : mAllActivitys) {
            if (activity.getClass().getName().equals(LoginActivity.class.getName())) {
                SystemSet.this.finish();
                return;
            }
        }
        Intent intent = new Intent(SystemSet.this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    public class TestTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String[] params) {

            Map<String, String> param = new HashMap<>();
            param.put("username", "admin");
            param.put("password", "adminadmin");
            String json = NetworkManager.postDataToServer(
                    "http://" + params[0] + ":" + params[1] + "/vehicleapi/WebService/LoginForComAndPer.ashx?", param);
            return getJson(json);
        }

        @Override
        protected void onPostExecute(String flag) {
            if (flag.equals("")) {
                AppUtils.showToastMessage(SystemSet.this, "IP或端口有误", Toast.LENGTH_SHORT);
            } else {
                SharedPreferences mSharedPreference = SystemSet.this.getSharedPreferences(
                        getString(R.string.preference_key), MODE_PRIVATE);
                SharedPreferences.Editor editor = mSharedPreference.edit();
                editor.putString(getString(R.string.label_system_set_ip), ip);
                editor.putString(getString(R.string.label_system_set_port), port);
                editor.commit();
                Constant.URI_BASH_PATH = "http://" + ip + ":" + port + "/vehicleapi/WebService/";
                AppUtils.setPath();
                AppUtils.showToastMessage(SystemSet.this, "设置成功", Toast.LENGTH_SHORT);
                mLoadingManager.EditIsFirstRun();
                exit();
            }
        }

        private String getJson(String json) {
            try {
                JSONArray jsonObject = new JSONArray(json);
                JSONObject jsonItem = jsonObject.getJSONObject(0);
                return jsonItem.getString("User_id");
            } catch (JSONException e) {
                return "";
            }
        }
    }
}
